import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';
import { CommonResponse, ObjectType } from 'src/types/index';
import * as jwt from 'jwt-simple';
const secret = 'zhufeng';

import { responseWrapper } from 'src/utils';

@Injectable()
export class LoginMiddleware implements NestMiddleware {
  // 登录中间件
  use(req: Request, res: Response, next: () => void) {
    const token = req.headers.token;
    console.log('中间件');
    if (!token) {
      res.json(responseWrapper('没有token', true));
      return;
    }
    // 校验token是否有效
    try {
      const payload = jwt.decode(token as string, secret);
      if (payload && payload.username) {
        const newToken = jwt.encode(payload, secret);
        if (token === newToken) {
          return next();
        }
      }
      throw new Error();
    } catch (error) {
      res.json(responseWrapper('token无效', true));
    }
  }
}
